package org.bbelovic.devel.exercises;

import java.util.Iterator;
import java.util.List;

public class FootballKataLineEvaluator implements LineEvaluator {

    public LineEvaluatorOutput evaluate(final LineEvaluatorInput input) {
        final List<String> lineTokens = input.getLineTokens();
        if (lineTokens.isEmpty()) {
            return new LineEvaluatorOutput(input.getCurrentValue(), input.getCurrentLine());
        }
        final int forPoints = Integer.parseInt(lineTokens.get(6));
        final int againstPoints = Integer.parseInt(lineTokens.get(7));
        final int referenceValue = input.getCurrentValue();
        if (forPoints - againstPoints < referenceValue) {
            return new LineEvaluatorOutput(forPoints - againstPoints, join(lineTokens));
        }
        return new LineEvaluatorOutput(referenceValue, input.getCurrentLine());
    }

    private String join(List<String> lineTokens) {
        if (lineTokens == null || lineTokens.isEmpty()) {
            return "";
        }
        final Iterator<String> it = lineTokens.iterator();
        final StringBuilder sb = new StringBuilder();
        if (it.hasNext()) {
            String first = it.next();
            if (first != null) {
                sb.append(first);
            }
        }
        if (!it.hasNext()) {
            return sb.toString();
        }
        while (it.hasNext()) {
            sb.append(" ")
              .append(it.next());
            
        }
        return sb.toString();
    }
}
